#include "../Core/Texture.h"
#include "../Core/MediaManager.h"

namespace epix {

Texture::Texture(GLuint texID, Vector2i size, int channels, unsigned char *data, const char *name) :
	IResource(name), _texID(texID), _size(size), _channels(channels), _data(data)
{
}

Texture::Texture(Vector2i size, unsigned char *data, const char *name) :
	IResource(name), _size(size), _channels(GL_RGBA), _data(data)
{
	glEnable(GL_TEXTURE_2D);
	
	glGenTextures(1, &_texID);
	
	glBindTexture(GL_TEXTURE_2D, _texID);
	
	gluBuild2DMipmaps(GL_TEXTURE_2D, 3, _size.X, _size.Y, GL_RGBA, GL_UNSIGNED_BYTE, data);
	
	glTexParameterf(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR_MIPMAP_LINEAR);
    glTexParameterf(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR_MIPMAP_LINEAR);
}

Texture::~Texture()
{
    if(_data) delete[] _data;
		glDeleteTextures(1, &_texID);
}

GLuint Texture::getGLID() const
{
    return _texID;
}

const Vector2i &Texture::getSize() const
{
    return _size;
}

int Texture::getChannels() const
{
    return _channels;
}

unsigned char *Texture::getData() const
{
    return _data;
}

void Texture::save(const char *filename)
{
	MediaManager::instance()->saveMedia<Texture>(this, filename);
}

}
